package cn.com.bsoft.kotlinEx

import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.MultiFormatWriter
import com.google.zxing.client.j2se.BufferedImageLuminanceSource
import com.google.zxing.common.BitMatrix
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import java.awt.image.BufferedImage



val BitMatrix.bufferedImage: BufferedImage
    get() {
        val BLACK = 0xff000000
        val WHITE = 0xFFFFFFFF

        val image = java.awt.image.BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_RGB)
        for (x in 0..width - 1) {
            for (y in 0..height - 1) {
                image.setRGB(x, y, if (get(x, y) === true) BLACK.toInt() else WHITE.toInt())
            }
        }
        return image
    }

fun BitMatrix.updateBit(margin: Int): BitMatrix {
    val tempM = margin * 2
    val rec = enclosingRectangle   //获取二维码图案的属性
    val resWidth = rec[2] + tempM
    val resHeight = rec[3] + tempM
    val resMatrix = BitMatrix(resWidth, resHeight) // 按照自定义边框生成新的BitMatrix
    resMatrix.clear()
    for (i in margin until resWidth - margin) {   //循环，将二维码图案绘制到新的bitMatrix中
        (margin until resHeight - margin)
                .filter { this.get(i - margin + rec[0], it - margin + rec[1]) }
                .forEach { resMatrix.set(i, it) }
    }
    return resMatrix
}

val BufferedImage.qrCode: String
    get() {
        val reader = QRCodeReader()
        val image = this
        val lumSource = BufferedImageLuminanceSource(image)
        val bitmap = BinaryBitmap(HybridBinarizer(lumSource))
        return reader.decode(bitmap).text
    }

val String.qrCode: BufferedImage
    get() {
        val byteMatrix = MultiFormatWriter().encode(this, BarcodeFormat.QR_CODE, 256, 256).updateBit(5)
        val image = byteMatrix.bufferedImage
        return image
    }